#define _GUN_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include "tlpi.h"

static void
handler(int sig)
{
	printf("PID=%ld: caught signal %2d(%s)\n", (long)getpid(), 
			sig, strsignal(sig));
}

int
main(int argc, char *argv[])
{
	int j;
	struct sigaction sa;

	if(argc < 2)
		fatal("usage error\n");

	setbuf(stdout, NULL);

	sa.sa_handler = handler;
	sa.sa_flags = 0;
	sigemptyset(&sa.sa_mask);
	if(sigaction(SIGHUP, &sa, NULL) == -1)
		errExit("sigaction() for SIGHUP failed");
	if(sigaction(SIGCONT, &sa, NULL) == -1)
		errExit("sigaction() for SIGCONT failed");

	printf("Parent: PID=%ld, PPID=%ld, PGID=%ld, SID=%ld\n", (long)getpid(),
			(long)getppid(), (long)getpgrp(), (long)getsid(0));

	for(j=1; j<argc; j++)
	{
		switch(fork())
		{
			case -1:
				errExit("fork() failed");

			case 0:
				printf("Child: PID=%ld, PPID=%ld, PGID=%ld, SID=%ld\n", (long)getpid(),
						(long)getppid(), (long)getpgrp(), (long)getsid(0));

				if(argv[j][0] == 's')
				{
					printf("Child PID=%ld stopping\n", (long)getpid());
					raise(SIGSTOP);
				}
				else
				{
					alarm(60);
					printf("PID=%ld pausing\n", (long)getpid());
					pause();
				}
				
				_exit(EXIT_SUCCESS);

			default:
				break;
		}
	}

	sleep(3);
	printf("parent exiting\n");
	exit(EXIT_SUCCESS);
}

